package database

import (
	"fmt"
	"mytest/models"
	"os"
	"path"

	"gorm.io/driver/mysql"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm/logger"

	"gorm.io/gorm"
)

var db *gorm.DB

func InitDatabsae(sqltype string) error {
	db = Gorm(sqltype)
	return db.AutoMigrate(
		&models.Student{},
		&models.SysOperationRecord{},
		&models.User{},
		&models.SysBaseMenu{},
		&models.SysAuthority{},
		&models.SysBaseMenuParameter{},
		&models.SysUser{},
		&models.BlackTokenList{},
		&models.SysApis{},
	)
}
func GetDB() *gorm.DB {
	return db
}
func Gorm(sqltype string) *gorm.DB {
	newLogger := logger.Default.LogMode(1)

	if sqltype == "mysql" {
		db, err := gorm.Open(mysql.Open("root:123456@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"), &gorm.Config{
			Logger: newLogger,
		})
		if err != nil {
			panic("failed to connect database")
		}
		return db
	}
	tmpDBFile := path.Join(os.TempDir(), "test.db")
	fmt.Println(tmpDBFile)
	os.Remove(tmpDBFile)

	db, err := gorm.Open(sqlite.Open(tmpDBFile), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		panic("failed to connect database")
	}
	return db
}
